package cn.lg.soar.common.util.current;

import lombok.Getter;

/**
 * 当前用户工具
 * @author luguoxiang
 * @date 2022/3/29
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
public class CurrentUser implements ICurrentUser {

    public final static String USER_KEY = "soar-cur-user";

    /**
     * 用户id
     */
    @Getter
    private Long id;

    /**
     * 用户类型
     */
    @Getter
    private Integer userType;

    /**
     * 当前租户
     */
    @Getter
    private Integer currentTenantId;

    /**
     * 载体
     */
    private Object[] payload;

    @Override
    public String getTokenId() {
        return (String) payload[0];
    }

    @Override
    public String getTokenValue() {
        return (String) payload[1];
    }

    @Override
    public Integer getClientType() {
        return (Integer) payload[5];
    }

    @Override
    public String getOtherInfo(int index) {
        final int LEN = 7;
        if (payload.length == LEN) {
            return null;
        }
        return (String) payload[LEN + index];
    }

    @Override
    public Object[] getPayload() {
        Object[] arr = new Object[payload.length];
        System.arraycopy(payload, 0, arr, 0, payload.length);
        return arr;
    }

    /**
     * 通过 token payload 构造
     * @param payload
     * @return
     */
    public static CurrentUser valueOf(Object[] payload) {
        CurrentUser currentUser = new CurrentUser();
        currentUser.payload = payload;
        currentUser.id = Long.parseLong((String) payload[2]);
        currentUser.userType = (Integer) payload[3];
        currentUser.currentTenantId = (Integer) payload[4];
        return currentUser;
    }
}
